//
//  Login.m
//  MUBATE
//
//  Created by sunbin on 2017/2/15.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "Login.h"
#import "LoginView.h"
#import "LoginModel.h"

#import "RootViewController.h"

@interface Login ()<LoginContainerViewDelegate>

@end

@implementation Login
{
    LoginView *container;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];

    container = (LoginView *)[NHUtils loadViewFormCtl:self view:[LoginView loginViewAccount:_account]];
    container.delegate = self;
    
    
}



#pragma make -LoginContainerViewDelegate 登录确认按钮事件0返回 1忘记密码 2登录
- (void)btnEven:(NSInteger)index account:(NSString *)account pwd:(NSString *)pwd{
    switch (index) {
        case 0:{}
            break;
        case 1:{
            //输入密码
            [NHUtils presentViewController:@"EnterAccount" ctl:self animationType:WXSTransitionAnimationTypeSysFade isSysBackAnimation:YES];
        }
            break;
        case 2:
            [self loginAccount:account password:pwd];
            break;
        default:
            break;
    }
}

// 登录
- (void)loginAccount:(NSString *)account password:(NSString *)pwd{
    WEAKSELF;
    
    [self.view showLoading:NSLocalizedString(@"Logging", @"Logging")];

    [[LoginModel shareInstance] loginWithAccount:account password:[pwd md5String] success:^(NSDictionary *loginresults, NSString *loginRequestmsg) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.view hideHUD];
            NSString *uid = TEXT_STRING([loginresults objectForKey:@"uid"]);
            [weakSelf loginSucceed:uid];
            [MBProgressHUD showSuccess:@"登录成功"];
        });
   
    } failure:^(NSDictionary *loginresults, responseState resMake, NSString *loginRequestError) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.view hideHUD];
            [CommonUtils showAlertWithTaget:weakSelf andMsg:loginRequestError];
        });
    }];


}


// 成功
- (void)loginSucceed:(NSString *)uid{
    WEAKSELF;
    [YConfig saveOwnID:uid];
    
    kAppDelegate.rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:kAppDelegate.rootViewController];
    [kAppDelegate.window addSubview:nav.view];
    [weakSelf.view removeFromSuperview];
    kAppDelegate.window.rootViewController = nav;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
